<?php
error_reporting(E_ALL);
include_once($relPath.'site_vars.php');
require_once $relPath."DpTable.class.php";
require_once $relPath."rounds.php";
require_once $relPath."links.inc";

// for page_detail.php
function echo_pagetable( $project, $userfilter = null )
{
    global $projects_dir, $pm_url;
    global $dpdb;
    global $User;
    global $ok;
    
    $projectid = $project->ProjectId();
    $tblrows = page_table_rows($project, $userfilter);

    echo_js($tblrows);


    $tbl = new DpTable();
    $tbl->SetClass("em90");
    $tbl->AddCaption(null, 4);  // leave one for the rownumber?
    $tbl->AddColumn("^ ", null, "rowchkbox", "width: 4em");
    $tbl->AddColumn("^"._("Page"), null, "imagelink", "skinny");
    // $tbl->AddColumn(">"._("Size"), null, "imagesize", "skinny");
    $tbl->AddColumn("^"._("Text"), null, "mastertextlink", "skinny");
    $tbl->AddColumn("^"._("Status"), null, "pagestate", "w4em");

    $i = 0;
    foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid)
    {
        $i++;
        $tbl->AddCaption("^".$roundid, 
                    $project->UserMayManage() ? 4 : 3);
        $tbl->AddColumn("^"._("Diff"), "$roundid", "difflink");
        $tbl->AddColumn("^"._("Date"), "time_{$i}", "roundtime");
        if($project->UserMayManage())
        {
            $tbl->AddColumn("^"._("User"), 
                                "$roundid", "usrlnk", "nopad");
        }
        $tbl->AddColumn(">"._("Text"), "r{$i}", "textlink");
        if($roundid == $project->RoundId())
            break;
    }
    if($project->UserMayManage())
    {
        $tbl->AddCaption("^"._("For PM"), 4);
        $tbl->AddColumn("^"._("Clear"), null, "clearlink");
        $tbl->AddColumn("^"._("Fix"), null, "fixlink");
        $tbl->AddColumn("^"._("Edit"), null, "editlink");
        if($User->IsSiteManager() || $project->UserIsPM())
        {
            $tbl->AddColumn("^"._("Delete"), null, "deletelink");
        }
    }
    else
    {
        $tbl->AddCaption("^".("Your<br/>pages"));
        $tbl->AddColumn("^"._("Edit"), "$roundid", "usreditlink");
    }

    $tbl->SetRows($tblrows);
    $tbl->EchoTableNumbered();
}

function page_table_rows($project, $userfilter)
{
    global $dpdb;
    global $User;

    $projectid = $project->ProjectId();
    $roundid = $project->RoundId();
    $roundindex = RoundIndexForId($roundid);

    if($userfilter)
    {
        $ids = array();
        $i = 1;
        foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid)
        {
            $ids[] = " Round{$i}_user = '{$userfilter}'\n";
            $i++;
        }
        // produce e.g. "round1_user = 'name' OR round2_user = ...
        $userclause = implode(" OR ", $ids);
    }

    $username = $userfilter ? $userfilter : $User->Username();
    
    $sql = "
        SELECT  
            '$projectid' as projectid,
            '$roundid' as roundid,
            '$username' as match_username,
            pp.fileid AS pagename,
            pp.image AS imagefile,
            pp.state AS pageroundstate,
            p.state AS projectroundstate,
            SUBSTRING(p.state, 1, 2) AS projectroundid,
            CHAR_LENGTH(pp.master_text) AS textlength_master,\n";

    // if($roundindex >= 1)
    // {
        $this_roundid = $project->RoundId();
        $i = 1;
        foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid)
        {
            $textfield = TextFieldForRoundIndex($i); 
            $prevtextfield = TextFieldForRoundIndex($i-1);
            $sql .= "
                pp.Round{$i}_user AS user_{$i},
                pp.Round{$i}_time AS time_{$i},
                CHAR_LENGTH(pp.Round{$i}_text) AS textlength_{$i},
                CASE WHEN pp.$textfield = pp.$prevtextfield 
                    THEN 0 ELSE 1 END AS is_diff_{$i},\n";
            // if($i >= $roundindex)
                // break;
            $i++;
        }
    // }

    $sql .= "
            pp.b_user,
            pp.b_code
        FROM pages AS pp
        JOIN projects AS p
            ON pp.projectid = p.projectid
        WHERE
            pp.projectid = '{$project->ProjectId()}'\n";
    
    $sql .= (empty($userfilter) ? "" : " AND ($userclause)\n");

    $sql .= "
        ORDER BY fileid\n";
    // say(PrettySql($sql));
    $rows = $dpdb->SqlRows($sql);
    return $rows;
}

function rowchkbox($pagerow)
{
    $name = 'selected_pages['.$pagerow['pagename'].']';
    return "<input type='checkbox' name='$name'>";
}

function imagelink($pagerow)
{
    $projectid  = $pagerow['projectid'];
    $pagename   = $pagerow['pagename'];

    return $pagerow['imagefile']
        ? link_to_display_image($projectid, $pagename, $pagename)
        : "<span class='danger'>"._("NO IMG!")."</span>";
}

function imagesize($pagerow)
{
    global $projects_dir;
    $projectid = $pagerow['projectid'];

    $imagefile = $pagerow['imagefile'];
    if(! $imagefile)
        return "<span class='danger'>"._("NO IMG!")."</span>";

    $imgpath = "$projects_dir/$projectid/$imagefile";
    return file_exists($imgpath)
        ? filesize($imgpath)
        : "<span class='danger'>"._("NO IMG!")."</span>";
}

function mastertextlink($pagerow)
{
    global $pm_url;
    $url = unamp("$pm_url/downloadproofed.php"
        ."?projectid={$pagerow['projectid']}"
        ."&pagename={$pagerow['pagename']}"
        ."&roundid=OCR");
    $ret = "<a target='_blank' href='{$url}"
        ."'>{$pagerow['textlength_master']}</a>";
    return $ret;
}

function textlink($idx, $pagerow)
{
    global $pm_url;
    $idx = substr($idx, 1);
    $roundid = RoundIdForIndex($idx);
    $key = "textlength_{$idx}";
    if(! isset($pagerow[$key]))
        return "";
    $url = unamp("$pm_url/downloadproofed.php"
            . "?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&roundid={$roundid}");
    return "<a target='_blank' href='$url"
            . "'>".$pagerow[$key]."</a>";
}


function pagestate($pagerow)
{
    $rs = $pagerow['pageroundstate'];
    $stat = preg_replace("/^.+?_/", "", $rs);
    if($stat == "out" || $stat == "temp")
    {
        $roundid = $pagerow['roundid'];
        $index = RoundIndexForId($roundid);
        $timefield = sprintf("time_%d", $index);
        $ptime = $pagerow[$timefield];
        $rsvtime = 4 * 60 - minutes_ago($ptime);
        if($rsvtime > 0)
        {
            $s_time = sprintf("%d:%2d", 
                            $rsvtime/60, $rsvtime%60);
        }
    }

    switch($stat)
    {
        case "avail":
            return "<div class='pg_available'>$stat</div>\n";

        case "bad":
            return "<div class='danger'>$stat</div>\n";

        case "out":
        case "temp":
            // return $rsvtime > 0
                // ? "<div class='status_out'>$s_time</div>\n"
                // : "<div class='status_avail'>avail</div>\n";
            return "<div class='pg_out'>out</div>\n";

        case "saved":
            return "<div class='pg_completed'>$stat</div>\n";

        default:
            return $stat;
    }
}

function pageroundid($pagerow)
{
    return preg_replace("/\..*$/", "", $pagerow['pageroundstate']);
}

function rounduser($fldname, $pagerow)
{
    return $pagerow[$fldname];
}

function roundtime($val, $page)
{
    return $val == 0
        ? ""
        : strftime( "%x %H:%M", intval($val) );
}

function clearlink($pagerow)
{
    global $pm_url;
    $url = unamp("$pm_url/edit_pages.php"
            ."?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&operation=clear");
    return "<a href='{$url}'>"._("Clear")."</a>";
}

function fixlink($pagerow)
{
    global $pm_url;
    $fix = _("Fix");

    $url = unamp("$pm_url/handle_bad_page.php"
            ."?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}");
    return "<a target='_blank' href='{$url}'>$fix</a>";
}

function editlink($row)
{
    global $proof_url;
    global $project;

    if($project->UserMayManage())
    {
        $edit = _("Edit");
        return link_to_proof_page($row['projectid'],
                                  $row['pagename'],
                                  $edit);
        /*
        $url = "$proof_url/proof.php"
                ."?projectid={$row['projectid']}"
                . "&pagename={$row['pagename']}";
        return "<a target='_blank' href='{$url}'>$edit</a>";
        */
    }
    else
    {
        return "";
    }
}

function usreditlink($roundid, $row)
{
    global $project;
    global $proof_url;

    if($roundid != $project->RoundId())
        return "";
    $match_username = $row['match_username'];
    $rindex = RoundIndexForId($roundid);
    $userval = $row["user_{$rindex}"];
    if($match_username != $userval)
        return "";
    $projectid = $project->ProjectId();
    $pagename = $row['pagename'];
    return link_to_proof_page($projectid, $pagename, "edit");
}

function deletelink($pagerow)
{
    global $pm_url;
    $url = unamp("$pm_url/edit_pages.php"
            ."?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&operation=delete");
    return "<a href='{$url}'>"._("Delete")."</a>";
}

function difflink($rindex, $pagerow)
{
    global $pm_url;
    $id = RoundIndexForId($pagerow['roundid']);
    $key = "textlength_{$id}";
    if(! isset($pagerow[$key]) || $pagerow[$key] == 0)
        return "";
    $key = "is_diff_{$id}";
    if( $pagerow[$key] == 0)
        return "no diff";

    $url = unamp("$pm_url/diff.php"
            ."?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&roundid={$rindex}");
    return "<a target='_blank' href='{$url}'>diff</a>";
}

function usrlnk($roundid, $page)
{
    $rindex = RoundIndexForId($roundid);
    $key = "user_{$rindex}";
    $username = $page[$key];
    // index for current round
    $pindex = RoundIndexForId(pageroundid($page));

    if(empty($username))
    {
        return "";
    }

    // username used in query - by mgmt?
    $matchname = $page['match_username'];

    if($matchname != $username)
    {
        return "<div class='notmypage'>$username</div>";
    }

    // current round?
    if($rindex != $pindex)
    {
        return "<div class='mypagedone'>$username</div>";
    }

    // based on page state ...
    switch(pagestate($page))
    {
        case "out":
        case "temp":
            return "<div class='mypageopen'>$username</div>"; 
        case "saved":
            return "<div class='mypagesaved'>$username</div>";
        default:
            return "<div class='mystery'>$username</div>";
    }
}

function echo_selection_combo()
{
    echo "
    <select onchange='changeSelection(this.options[this.selectedIndex].value)' name='select'>
        <option value='0'>Select...</option>
        <option value='all'>Select all</option>
        <option value='unproofed'>Select all unproofread</option>
        <option value='invert'>Invert selection</option>
        <option value='clear'>Clear selection</option>
    </select>\n";
}

function echo_action_combo()
{
    echo "
    <select name='operation'>
        <option value='clear'>Clear</option>
        <option value='delete'>Delete</option>
    </select>\n";

}

function echo_js($rows)
{
    $num_rows = count($rows);
    
    ?>
<script>

    var avail_pages = new Array();
    <?php 
    foreach($rows as $row)
    {
        if(pagestate($row) == 'avail')
            echo "avail_pages.push('{$row['pagename']}')\n";
    }
    ?>
    var i;

    function changeSelection(sel) 
    {
        switch(sel) {
            case "all":
                for(i=1;i<= <?php echo $num_rows; ?>; i++)
                    document.pagesform.elements[i].checked=true;
                break;
            case "unproofed":
                changeSelection("clear");
                for(i in avail_pages)
                    document.pagesform.elements[avail_pages[i]].checked=true;
                break;
            case "invert":
                for(i = 1; i <= <?php echo $num_rows; ?>; i++)
                    document.pagesform.elements[i].checked=!document.pagesform.elements[i].checked;
                break;
            case "clear":
                for(i = 1; i <= <?php echo $num_rows; ?>; i++)
                    document.pagesform.elements[i].checked=false;
                break;
            default:
                break;
        }
    }
</script>
<?php
}

// for edit_pages.php
function echo_page_review_table($project, $include)
{
    global $dpdb;

    $projectid  = $project->ProjectId();
    $roundid    = $project->RoundId();
    $roundindex = RoundIndexForId($roundid);

    $sql = "
        SELECT  
            '$projectid' as projectid,
            '$roundid' as roundid,
            pp.fileid AS pagename,
            pp.image AS imagefile,
            pp.state AS pageroundstate,
            CHAR_LENGTH(pp.master_text) AS textlength_master,\n";

    if($roundindex >= 1)
    {
        $this_roundid = $project->RoundId();
        $i = 1;
        foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid)
        {
            $textfield = TextFieldForRoundIndex($i); 
            $prevtextfield = TextFieldForRoundIndex($i-1);
            $sql .= "
                pp.Round{$i}_user AS user_{$i},
                pp.Round{$i}_time AS time_{$i},
                CHAR_LENGTH(pp.Round{$i}_text) AS textlength_{$i},
                CASE WHEN pp.$textfield = pp.$prevtextfield 
                    THEN 0 ELSE 1 END AS is_diff_{$i},\n";
            if($i >= $roundindex)
                break;
            $i++;
        }
    }

    $sql .= "
            pp.b_user,
            pp.b_code
        FROM pages AS pp
        JOIN projects AS p
            ON pp.projectid = p.projectid
        WHERE
            pp.projectid = '{$project->ProjectId()}'
        ORDER BY fileid\n";

    $tblrows = $dpdb->SqlRows($sql);

    $userows = array();
    foreach($tblrows as $index => $row)
    {
        $key = $row["pagename"];
        if(! empty($include[$key]))
        {
            $userows[] = $row;
        }
    }

    $tbl = new DpTable();
    $tbl->AddCaption("legend", 5);  // leave one for the rownumber?
    $tbl->AddColumn("^"._("Page"), null, "imagelink", "skinny");
    $tbl->AddColumn("^"._("Text"), null, "mastertextlink", "skinny");
    $tbl->AddColumn("^"._("Status"), null, "pagestate",  "w4em");

    $i = 0;
    foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid)
    {
        $i++;
        $tbl->AddCaption("^".$roundid, 4);
        $tbl->AddColumn("^"._("Diff"), "$roundid", "difflink");
        $tbl->AddColumn("^"._("Date"), "time_{$i}", "roundtime");
        $tbl->AddColumn("^"._("Proofer"), "user_{$i}", "userdisplay");
        $tbl->AddColumn(">"._("Text"), "r{$i}", "textlink");
        if($roundid == $project->RoundId())
            break;
    }

    $tbl->SetRows($userows);
    $tbl->EchoTableNumbered();
        
}

function userdisplay($username, $page)
{
    global $forum_url;
    return empty($username)
        ? ""
        : "<a target='_blank' 
        href='{$forum_url}/privmsg.php?mode=post'>$username</a>\n";
}

?>
